﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class HeadCenter : MonoBehaviour
{
    public GameObject curRail;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        var obj = collision.gameObject;
        var rail = obj.GetComponents<Rail>();
        if (rail.Length > 0)
        {
            var headstate = GetComponentInParent<Head>().state;
            var railstate = rail[0].state;
            if (headstate == railstate)
            {
                Debug.Log("Touch rail!");
                GetComponentInParent<Head>().onRail = true;
                GetComponentInParent<Head>().GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
                curRail = obj;
            }
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        Debug.Log("QAQ");
        Debug.Log(collision.gameObject);
        var obj = collision.gameObject;
        var rail = obj.GetComponents<Rail>();
        if (rail.Length > 0 && obj == curRail)
        {
            Debug.Log("Leave rail!");

            GetComponentInParent<Head>().onRail = false;
            GetComponentInParent<Head>().GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
        }
    }
}